package com.netty.netty;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * @Author: CaiXiang
 * @Date: 2019/5/23 11:16
 * @Version 1.0
 * @Description:
 */
public class ClientHandler {
    public static final int MAX_DATALEN = 1024;
    private final Socket socket;
    public ClientHandler(Socket socket){
        this.socket = socket;
    }
    public void start(){   //对于start 方法，每个连接进来的客户端，都会这么去创建一个线程。
        System.out.println("新客户端接入");
        new Thread(new Runnable() {
            @Override
            public void run() {
                doStart();
            }
        }).start();
    }

    private void doStart(){
        try {
            InputStream inputStream = socket.getInputStream();  //拿到一个socket 的输入流然后循环的去读这个输入流
            while (true){
                byte[] data = new byte[MAX_DATALEN];
                int len;
                while((len = inputStream.read(data))!=-1){
                    String message = new String(data,0,len);
                    System.out.println("客户端传来的消息："+message);
                    socket.getOutputStream().write(data);
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

}
